package centaline.api.utils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.util.ArrayList;
import java.util.Map;
import java.util.Map.Entry;

public class HttpUtils {

	public static String doPost(String url, Map<String, String> map) {
		return HttpUtils.doPost(url, map,null);
	}

	public static String doPost(String url, Map<String, String> map, String charset) {

		charset = (charset==null)?"UTF-8":charset;

		HttpClient client = HttpClients.createDefault();
		HttpPost post = new HttpPost(url);

		try {
			//post要提交的参数
			ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>();
			for(Entry<String,String> entry:map.entrySet()){
				pairs.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
			}
			// 设置提交编码
			post.setEntity(new UrlEncodedFormEntity(pairs,charset));

			System.out.println("===========请求方式===========");
			System.out.println(post.getRequestLine().toString());

			// 创建response接收返回值
			HttpResponse response = client.execute(post);
			HttpEntity entity = response.getEntity();
			String result = EntityUtils.toString(entity,charset);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
}
